package client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import event.Event;
import event.EventHandler;

public class PeerServer implements Runnable {

	private static final int NTHREADS_CLIENTS = 5;

	// Use a thread pool to handle client connections.
	private static final Executor clientExecutor = Executors
			.newFixedThreadPool(NTHREADS_CLIENTS);

	private ServerSocket mSocket;
	private boolean mReadyForConnections = false;

	public PeerServer(int port) throws IOException {
		mSocket = new ServerSocket(port);

		startServer();
	}

	public void startServer() {
		mReadyForConnections = true;

		Thread thread = new Thread(this);
		thread.start();
	}

	public void cancel() {
		mReadyForConnections = false;
	}

	@Override
	public void run() {
		System.out.println("> available for peer connections");

		while (mReadyForConnections) {
			// Block until client connects.
			try {
				Socket clientSocket = mSocket.accept();

				// Handle the client requests.
				PeerHandler handler = new PeerHandler(clientSocket);

				clientExecutor.execute(handler);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
